#ifndef RESULT_H
#define RESULT_H
#include "semphore.h"
#include "task.h"
#include <string>
#include <memory>
#include <atomic>
class Any
{
private:
    class Base
    {
    public:
        virtual ~Base() = default;
    };
    template <typename T>
    class Deriver : public Base
    {
    public:
        T data_;
        Deriver(T data) : data_(data)
        {
        }
    };
    std::unique_ptr<Base> base_;

public:
    Any() = default;
    ~Any() = default;
    Any(const Any &) = delete;            // 禁用拷贝构造
    Any &operator=(const Any &) = delete; // 禁用拷贝赋值
    Any(Any &&) = default;
    Any &operator=(Any &&) = default;
    template <typename T>
    Any(T data) : base_(std::make_unique<Deriver<T>>(data))
    {
    }

    template <typename T>
    T cast_()
    {
        Deriver<T> *pd = dynamic_cast<Deriver<T> *>(base_.get());
        if (pd == nullptr)
        {
            throw "type is unmatch";
        }
        return pd->data_;
    }
};
//两个对象互相使用强智能指针，会导致无法释放，导致内存泄漏 ！！！！！！
class Task; // Task 前置声明
class Result
{
public:
    Result(std::shared_ptr<Task> task, bool isValid = true);
    ~Result() = default;
    //问题1: setvalue方法，获取任务执行完的返回值
    void setValue(Any any);
    //问题2: get方法,用户调用这个方法获取task的返回值
    Any get();
private:
    Any any_;                    // 任务返回值
    Semphore sem_;               // 信号量
    std::shared_ptr<Task> task_; // 指向对应task的result
    std::atomic_bool isValid_;   // 返回值是否有效
};

#endif // RESULT_H ///:~